#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#include "list.h"
#include <mcheck.h>

typedef struct _DATA_
{
    int len;
    char buff[];
} DATA_t;

void free_data(void* _data)
{
    DATA_t* data = (DATA_t*)_data;
    if(NULL == data)
        return;
    free(data);
}

int main()
{
    setenv("MALLOC_TRACE", "/tmp/mem.txt", 1);
    mtrace();

    LIST_t *list = create_list(10, 248, free_data);
    if (NULL == list)
    {
        printf("Create list error\n");
        exit(-1);
    }
    
    for(int i = 0; i < 2; i++)
    {
        char *num_str = NULL;
        asprintf(&num_str, "%d", i);
        if(num_str == NULL)
        {
            printf("Create num error\n");
            exit(-1);
        }
        
        DATA_t *data = (DATA_t *)malloc(sizeof(DATA_t) + strlen(num_str) * sizeof(char) + 1);
        if (NULL == data)
        {
            printf("Create data error\n");
            exit(-1);
        }
        bzero(data, sizeof(DATA_t) + strlen(num_str) * sizeof(char) + 1);
        data->len = strlen(num_str);
        strcpy(data->buff, num_str);
        int err = list->push_back(list, data, sizeof(DATA_t) + data->len * sizeof(char) + 1);
        if(err < 0)
            printf("push back error, errcode:%d", err);
        
        free(num_str);
        free(data);
    }

    printf("list size:%d\n", list->size(list));
    while(!list->empty(list))
    {
        DATA_t *it = (DATA_t *)list->front(list);
        if (NULL == it)
        {
            printf("Get front error\n");
            exit(-1);
        }
        printf("len:%d, buff:%.*s\n", it->len, it->len, it->buff);

        list->pop_front(list);
    }
    printf("list size:%d\n", list->size(list));
    list->clear(list);
    printf("list size:%d\n", list->size(list));
    list->destruct(&list);
    muntrace();
}
